package com.gitee.apanlh.util.net.http;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.valid.ValidParam;

import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

/**
 * 	HTTP响应头	
 * 
 * 	@author Pan
 */
public class HttpResponseHeader extends HttpHeader<List<String>> {
	
	/**
	 * 	构造函数-继承抽象类
	 * 	
	 * 	@author Pan
	 */
	public HttpResponseHeader() {
		super();
	}
	
	/**
	 * 	构造函数-继承抽象类
	 * 	<br>自定义Map
	 * 	
	 * 	@author Pan
	 * 	@param 	map map
	 */
	public HttpResponseHeader(Map<String, List<String>> map) {
		super(map);
	}
	
	/**
	 * 	构造函数-加载响应头信息
	 * 	
	 * 	@author Pan
	 * 	@param 	httpClient	HttpURL客户端
	 */
	public HttpResponseHeader(HttpURLConnection httpClient) {
		super(MapUtils.newLinkedHashMap(httpClient.getHeaderFields()));
		//	添加状态行
		List<String> list = get(null);
		
		if (!ValidParam.isEmpty(list)) {
			String[] split = StringUtils.split(CollUtils.toStr(list, " "), " ");
			
			add("StatusLine", list);
			add("StatusLineProtocol", CollUtils.newArrayList(split[0]));
			add("StatusLineCode", CollUtils.newArrayList(split[1]));
			add("StatusLineDesc", CollUtils.newArrayList(split[2]));
			remove(null);
		}
	}

	/**	
	 * 	获取请求头
	 * 	<br>如果遇到多个参数则用 ; 分割
	 * 	
	 * 	@author Pan
	 * 	@return	Map
	 */
	public Map<String, String> getHeaderSingleMap() {
		return MapUtils.newLinkedHashMap(newMap -> IteratorUtils.entrySet(getHeaderMap(), (key, values) -> {
			StringBuilder sb = StringUtils.createBuilder();
			
			for (int i = 0; i < values.size(); i++) {
				sb.append("[");
				sb.append(values.get(i));
				sb.append("]; ");
			}
			
			newMap.put(key, sb.toString());
		}));
	}
	
	/**	
	 * 	创建-默认使用LinkedHashMap
	 * 	<br>自动加载响应头信息
	 * 	
	 * 	@author Pan
	 * 	@param	httpClient  HttpURLConnection
	 * 	@return	HttpResponseHeader
	 */
	public static HttpResponseHeader create(HttpURLConnection httpClient) {
		return new HttpResponseHeader(httpClient);
	}
}
